package com.xqboss.apps.controller.consumer;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.xqboss.apps.domain.consumer.ConsumerInviteRecord;
import com.xqboss.apps.dto.PageDto;
import com.xqboss.apps.dto.consumer.ContactsUploadDto;
import com.xqboss.apps.dto.consumer.SetPushIdDto;
import com.xqboss.apps.dto.team.TeamInviteJoinDto;
import com.xqboss.apps.dto.user.UserRealNameDto;
import com.xqboss.apps.service.consumer.*;
import com.xqboss.apps.service.user.UserPushBindService;
import com.xqboss.apps.vo.consumer.ConsumerInviteRecordVo;
import com.xqboss.apps.vo.sys.SysUserVo;
import com.xqboss.apps.vo.user.UserRealNameStatusVo;
import com.xqboss.common.annotation.Anonymous;
import com.xqboss.common.annotation.Log;
import com.xqboss.common.annotation.RepeatSubmit;
import com.xqboss.common.core.controller.BaseController;
import com.xqboss.common.core.domain.R;
import com.xqboss.common.core.domain.entity.SysUser;
import com.xqboss.common.core.domain.model.LoginBody;
import com.xqboss.common.enums.BusinessType;
import com.xqboss.common.utils.SecurityUtils;
import com.xqboss.common.utils.StringUtils;
import com.xqboss.framework.web.service.SysRegisterService;
import com.xqboss.system.mapper.SysUserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 用户实名认证Controller
 *
 * @author xqboss
 * @date 2023-08-08
 */
@Api(tags = {"用户管理"})
@RestController
@RequestMapping("/apps/consumer")
public class ConsumerController extends BaseController {

    @Autowired
    private ConsumerRealNameService consumerRealNameService;
    @Autowired
    private ConsumerContactsService consumerContactsService;
    @Autowired
    private SysRegisterService sysRegisterService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private ConsumerService consumerService;
    @Autowired
    private ConsumerInviteRecordService consumerInviteRecordService;
    @Autowired
    private UserPushBindService userPushBindService;
    @Autowired
    private ConsumerTeamMemberService consumerTeamMemberService;
    @Autowired
    private ConsumerTeamService consumerTeamService;

    @RepeatSubmit(interval = 1000, justUrl = true)
    @ApiOperation("用户实名认证接口")
    @PostMapping("/real-name")
    public R<UserRealNameStatusVo> realName(@Validated @RequestBody UserRealNameDto dto) {
        Long userId = getUserId();
        UserRealNameStatusVo vo = consumerRealNameService.realName(dto.getIdCardName(), dto.getIdCard(), userId, dto.getMetaInfo(), dto.getReturnUrl());
        return R.ok(vo);
    }

    @ApiOperation("同步实名认证状态")
    @PostMapping("/sync-real")
    public R<UserRealNameStatusVo> syncReal(@Validated @RequestBody Object obj) {
        UserRealNameStatusVo vo = consumerRealNameService.syncUserRealNameStatus(getUserId());
        return R.ok(vo);
    }

    @ApiOperation("身份验证")
    @PostMapping("/authentication")
    public R authentication(@ApiParam(name = "idCardName", value = "身份证姓名", required = true)
                            @RequestParam String idCardName,
                            @ApiParam(name = "idCard", value = "身份证号", required = true)
                            @RequestParam String idCard) {
        Long userId = getUserId();
        return consumerRealNameService.authentication(idCardName, idCard, userId);
    }

    @RepeatSubmit(interval = 1000, justUrl = true)
    @ApiOperation("通讯录上传")
    @PostMapping("/contacts-upload")
    public R contactsUpload(@RequestBody ContactsUploadDto dto) {
        dto.setUserId(getUserId());
        return consumerContactsService.contactsUpload(dto);
    }

    @RepeatSubmit(interval = 1000, justUrl = true)
    @ApiOperation("换绑手机号")
    @PostMapping("/change-phone")
    public R changePhone(@ApiParam(name = "userName", value = "换绑的手机号", required = true)
                         @RequestParam String userName,
                         @ApiParam(name = "code", value = "验证码", required = true)
                         @RequestParam String code,
                         @ApiParam(name = "businessType", value = "业务类型", required = true)
                         @RequestParam String businessType) {
        return sysRegisterService.changePhone(userName, code, businessType);
    }

    @RepeatSubmit(interval = 1000, justUrl = true)
    @Log(title = "注销用户", businessType = BusinessType.DELETE)
    @ApiOperation("注销用户")
    @DeleteMapping("/logout")
    public R logoutUser() {
        Long userId = getUserId();
        String number = RandomUtil.randomNumbers(6);
        sysUserMapper.logoutUser(userId, "_" + number);
        //清除实名信息
        consumerRealNameService.deleteByUserId(userId);
        //清除队伍
        Long teamId = consumerTeamMemberService.getTeamIdByUserId(userId);
        if (Objects.nonNull(teamId)) {
            consumerTeamService.quit(Math.toIntExact(teamId), userId);
        }
        return R.ok();
    }

    @RepeatSubmit(interval = 1000, justUrl = true)
    @Log(title = "v2注销用户", businessType = BusinessType.UPDATE)
    @ApiOperation("v2注销用户")
    @PostMapping("/v2/logout")
    public R v2LogoutUser(@RequestBody LoginBody params) {
        return consumerService.v2Logout(getUserId(), params);
    }

    @ApiOperation("邀请记录列表")
    @PostMapping("/invite-record")
    public R<List<ConsumerInviteRecordVo>> inviteRecord(@RequestBody PageDto dto) {
        Long userId = getUserId();
        dto.startPageAndOrder();
        List<ConsumerInviteRecordVo> vo = consumerInviteRecordService.inviteRecord(userId);

        return R.ok(vo);
    }

    @ApiOperation("我的邀请人")
    @GetMapping("/my-invite")
    public R<SysUserVo> myInvite() {
        Long userId = getUserId();
        SysUser user = sysUserMapper.selectUserById(userId);
        if (ObjUtil.isNotNull(user) && ObjUtil.isNotNull(user.getInviterId())) {
            SysUser invite = sysUserMapper.selectUserById(user.getInviterId());
            SysUserVo vo = BeanUtil.copyProperties(invite, SysUserVo.class);
            return R.ok(vo);
        }
        return R.ok();
    }

    @RepeatSubmit(interval = 1000, justUrl = true)
    @ApiOperation("绑定邀请人")
    @PutMapping("/bind-invite")
    public R bindInvite(@ApiParam(name = "invitationCode", value = "邀请码", required = true)
                        @RequestParam String invitationCode) {
        return consumerService.bindInvite(getUserId(), invitationCode);
    }

    @ApiOperation("设置推送设备号")
    @PostMapping("/set-push-id")
    public R setPushId(@RequestBody @Validated SetPushIdDto dto) {
        if(StringUtils.isNotEmpty(dto.getRegistrationId())){
            userPushBindService.bindUserPushId(getUserId(), dto.getRegistrationId());
        }
        return R.ok();
    }

    @RepeatSubmit(interval = 1000, justUrl = true, message = "访问过于频繁，请稍后再试")
    @ApiOperation("邀请加入队伍")
    @PostMapping("/invite-join-team")
    @Anonymous
    public R inviteJoinTeam(@Validated @RequestBody TeamInviteJoinDto params) {
        return consumerTeamMemberService.inviteJoinTeam(getUserId(), params);
    }
}

